package com.gitee.xmhzzz.component.shutdown.graceful.xxljob;

import com.gitee.xmhzzz.component.shutdown.graceful.event.ApplicationShutdownEvent;
import com.xxl.job.core.executor.impl.XxlJobSpringExecutor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.ApplicationContext;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

/**
 * @ClassName XxlJobShutdown
 * @Description
 * @Author wzq
 * @Date 2023/9/25 13:38
 * @Version 1.0
 */
@Slf4j
@Component
@ConditionalOnClass(XxlJobSpringExecutor.class)
@ConditionalOnBean(XxlJobSpringExecutor.class)
@ConditionalOnProperty(value = "xmhzzz.graceful.shutdown.enable", havingValue = "true")
public class XxlJobShutdown {

    private volatile boolean shutdown = false;

    public XxlJobShutdown() {
        log.info("init XxlJobShutdown");
    }

    @EventListener
    public void shutdownEventListener(ApplicationShutdownEvent event) {
        try {
            if (!this.shutdown) {
                this.shutdown = true;
                Long beginTime = System.currentTimeMillis();
                ApplicationContext applicationContext = (ApplicationContext) event.getSource();
                XxlJobSpringExecutor xxlJobSpringExecutor = applicationContext.getBean(XxlJobSpringExecutor.class);
                if (xxlJobSpringExecutor == null) {
                    return;
                }
                log.info("xxlJob start  beginTime [{}]", beginTime);
                xxlJobSpringExecutor.destroy();
                long consumingTimeTotal = System.currentTimeMillis() - beginTime;
                log.info("xxlJob shutdown time [{}](ms)", consumingTimeTotal);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

    }
}

